import React, { ChangeEvent, FC, useEffect, useState } from "react";
import { useNavigate, useLocation, useSearchParams } from "react-router-dom";
import { Input } from "antd";
import { LIST_SEARCH_PARAM_KEY } from "../constant";

const { Search } = Input;
const ListSearch: FC = () => {
  const nav = useNavigate();
  const { pathname } = useLocation();
  const [Value, setValue] = useState<string>("");
  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    setValue(e.target.value);
  }
  function handleSearch(value: string) {
    // 跳转页面并且添加url参数
    nav({
      pathname,
      search: `${LIST_SEARCH_PARAM_KEY}=${value}`,
    });
  }
  // 获取 url 参数，并设置到 input value
  const [searchParams] = useSearchParams();
  useEffect(() => {
    const curVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || "";
    setValue(curVal);
  }, [searchParams]);

  return (
    <div>
      <Search
        allowClear
        placeholder="请输入内容"
        size="large"
        value={Value}
        onChange={handleChange}
        onSearch={handleSearch}
      />
    </div>
  );
};

export default ListSearch;
